import os
import json
from openai import OpenAI
import time
import sys

# 读取提示词文件
def read_prompt_file(prompt_file='prompt.md'):
    try:
        with open(prompt_file, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception as e:
        print(f"读取提示词文件失败: {str(e)}")
        # 如果无法读取文件，返回默认提示词
        return "你是一位专业的知识讲解助手，擅长将复杂的概念解释得清晰易懂。请根据用户提供的内容，生成一份详细、准确且易于理解的解释。"

# 调用DeepSeek API生成解释
def generate_explanation(user_input, system_prompt):
    # 读取环境变量中的API密钥或使用默认密钥
    api_key = os.getenv('DEEPSEEK_API_KEY', 'sk-751ae345bc8440f48b5231ed222409b8')
    
    try:
        # 初始化OpenAI客户端
        client = OpenAI(api_key=api_key, base_url="https://api.deepseek.com")
        
        # 准备消息
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_input},
        ]
        
        print("正在生成解释，请稍候...")
        
        # 发送请求
        response = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            stream=False
        )
        
        # 获取响应内容
        explanation = response.choices[0].message.content
        
        # 保存为MD文件
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"explanation_{timestamp}.md"
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(f"# 解释内容\n\n{explanation}")
        
        print(f"解释已保存为: {filename}")
        print("\n===== 解释结果 =====")
        print(explanation)
        print("====================")
        
        return explanation, filename
        
    except Exception as e:
        error_message = f"生成解释时出错: {str(e)}"
        print(error_message)
        return None, None

# 命令行界面
def main():
    print("=== DeepSeek 解释助手 ===")
    print("请输入您想要解释的内容，输入'q'退出程序。")
    
    # 读取提示词
    system_prompt = read_prompt_file()
    
    while True:
        print("\n")
        user_input = input("您的问题或内容: ")
        
        if user_input.lower() == 'q':
            print("感谢使用DeepSeek解释助手，再见！")
            break
        
        if not user_input or user_input.strip() == '':
            print("请输入有效的内容。")
            continue
        
        # 生成解释
        explanation, filename = generate_explanation(user_input, system_prompt)
        
        if explanation:
            print(f"\n解释已成功生成并保存到文件: {filename}")
        else:
            print("生成解释失败，请重试。")

if __name__ == "__main__":
    main()